package com.ys.web.hjzf.controller;

import com.ys.base.EnumType;
import com.ys.utils.alipay.model.MsgInfo;
import com.ys.utils.annotation.UserPayGroupNumberCheck;
import com.ys.utils.base.http.ResponseHandler;
import com.ys.utils.base.j2se.DateUtil;
import com.ys.utils.base.j2se.MapHandler;
import com.ys.utils.base.j2se.StringHandler;
import com.ys.utils.hjzf.HjzfHandler;
import com.ys.utils.hjzf.sdk.utils.JsonUtil;
import com.ys.utils.http.RSAUtils;
import com.ys.utils.redis.Redis;
import com.ys.utils.redis.key.UserKey;
import com.ys.utils.spring.config.SystemError;
import com.ys.utils.spring.properties.Config;
import com.ys.web.goods.order.service.OrderService;
import com.ys.web.hjzf.service.HjzfService;
import com.ys.web.mobao.model.po.BindCard;
import com.ys.web.mobao.model.po.MobaoRechargeCreate;
import com.ys.web.pay.PayEnum;
import com.ys.web.pay.PayService;
import com.ys.web.pay.manager.PayManager;
import com.ys.web.pay.model.PayOrder;
import com.ys.web.pay.model.vo.UserBank;
import com.ys.web.user.login.LoginInfo;
import com.ys.web.user.login.LoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RequestMapping("/hjzf/")
@RestController
@Slf4j
public class HjzfController {

    @Autowired
    private PayService payService;
    @Autowired
    private HjzfService hjzfService;
    @Autowired
    private LoginService loginService;
    @Autowired
    private OrderService orderService;


    @RequestMapping("user/bind/bank")
    public String bindBank(@RequestAttribute String uid,
                                   BindCard bindCard) {
        if (Boolean.parseBoolean(Config.pp.get("trading.disable"))) {
            SystemError.wrapBs("500", "交易系统已关闭");
        }
        int count = hjzfService.getUserBankCheckCardNo(bindCard.getCardNo());
        if (count > 0) {
            SystemError.wrapBs("500", "该卡已绑定");
        }
        bindCard.setUserId(uid);
        bindCard.setCardNo(bindCard.getCardNo().replaceAll(" ", ""));
        bindCard.setCardToken(bindCard.getRequestId());
        MsgInfo msgInfo = HjzfHandler.signSms(bindCard);
        if(msgInfo.isSuccess){
//            hjzfService.saveUserBank(bindCard);
            Redis.str.set("user:bind:bank:"+bindCard.cardToken, JsonUtil.toString(bindCard),10*60);
        }else{
            SystemError.wrapBs("500", "绑卡失败");
        }
        return ResponseHandler.success(MapHandler.initMap("cardToken", bindCard.getCardToken(), "signData", ""));
    }

    @RequestMapping("user/bind/bank/sms/sign")
    public String smsSign(@RequestAttribute String uid,
                           String cardToken,String smsCode) {
        if (Boolean.parseBoolean(Config.pp.get("trading.disable"))) {
            SystemError.wrapBs("500", "交易系统已关闭");
        }
        String bank = Redis.str.get("user:bind:bank:"+cardToken);
        if(StringHandler.isEmpty(bank)){
            SystemError.wrapBs("500", "请重新绑定");
        }
        BindCard bindCard = JsonUtil.toBean(bank,BindCard.class);
        MsgInfo msgInfo = HjzfHandler.smsSign(cardToken,smsCode);
        if(msgInfo.isSuccess){
            bindCard.userId = uid;
            bindCard.linkId = msgInfo.thirdOrder;
            bindCard.bankCode = msgInfo.payFundOrderId;
            bindCard.cardToken = cardToken;
            hjzfService.saveUserBank(bindCard);
            Redis.key.del("user:bind:bank:"+cardToken);
//            hjzfService.updateUserBank(bindCard);
        }else{
//            hjzfService.delUserBankByCardToken(StringHandler.getLong(uid),cardToken);
            SystemError.wrapBs("500", "绑卡失败...");
        }

        return ResponseHandler.success();
    }

    @RequestMapping("user/unbind/bank")
    public String unbind(@RequestAttribute String uid,BindCard bindCard) {
        if (Boolean.parseBoolean(Config.pp.get("trading.disable"))) {
            SystemError.wrapBs("500", "交易系统已关闭");
        }
        LoginInfo loginInfo = loginService.infoByUid(uid);
        if (!PayManager.validatePayPassword(RSAUtils.decryptField(bindCard.getPayPassword()), loginInfo)) {
            SystemError.wrapBs(EnumType.ResponseCode.ILLEGAL.getCode(), "支付密码错误");
        }
        MsgInfo msgInfo = HjzfHandler.unSign(bindCard.linkId,1);
        if(msgInfo.isSuccess){
            hjzfService.delUserBankByCardToken(StringHandler.getLong(uid),bindCard.getCardToken());
        }else{
            SystemError.wrapBs("500", "解绑失败");
        }

        return ResponseHandler.success();
    }

    @RequestMapping("user/bank/query")
    public String query(@RequestAttribute long uid) {
        List<UserBank> list = hjzfService.getUserBankByUserId(uid);
        list = list.stream().peek(x -> {
            x.setCardNo(x.getCardNo().substring(x.getCardNo().length()-4));
            x.setMobile(null);
            x.setIdCardNum(null);
            x.setUserId(null);
        }).collect(Collectors.toList());
        return ResponseHandler.list(list);
    }



    @UserPayGroupNumberCheck
    @RequestMapping("pay/sms")
    public String paySms(@RequestAttribute String uid, @RequestAttribute String ip, MobaoRechargeCreate rechargeCreate,
                            @RequestParam(defaultValue = "")String passWord){
        if (Boolean.parseBoolean(Config.pp.get("trading.disable"))) {
            SystemError.wrapBs("500", "系统维护,交易系统已关闭");
        }
        rechargeCreate.payChannel="hjzf";
        //如果是红包或者转账，有限判定入参准确性
        int dayKey = StringHandler.getInt(DateUtil.getYYMMDD());
        String key = UserKey.rechargeHjzfCreateKey(dayKey, uid);
        String hjzfMoneyAllKey = UserKey.rechargeCreateHjzfMoneyAllKey(dayKey, uid);
        String hjzfMoneyDayAllKey = UserKey.rechargeFreeHjzfDayKey(dayKey);
        String hjzfAllKey = UserKey.rechargeCreatehHzfMoneyAllKey(dayKey/100, 0);
        if(!rechargeCreate.whiteList(uid)) {
            if (Boolean.parseBoolean(Config.pp.get("wallet.account.hjzf.recharge"))) {
                SystemError.wrapBs("500", "充值功能暂时已关闭");
            }
            if (rechargeCreate.getBusinessType() == 1) {
                int count = StringHandler.getInt(Redis.str.get(key));
                if (count > 0) {
                    String setCount = Config.pp.get("wallet.recharge.money.hjzf.day.num");
                    if (count >= Integer.parseInt(setCount)) {
                        SystemError.wrapBs(EnumType.ResponseCode.Fail.getCode(), "充值失败，每日最多充值" + setCount + "次");
                    }
                }
                String hjzAllMoney = Redis.str.get(hjzfAllKey);
                if (StringHandler.isNotEmpty(hjzAllMoney)) {
                    long hjzfAll = StringHandler.getLong(Config.pp.get("wallet.recharge.money.hjzf.all.money"));
                    if (hjzfAll > 0) {
                        if (StringHandler.getLong(StringHandler.isEmpty(hjzAllMoney) ? 0 : StringHandler.fenToLi(hjzAllMoney)) + StringHandler.parseMoney(rechargeCreate.getAmount()) > hjzfAll) {
                            SystemError.wrapBs(EnumType.ResponseCode.Fail.getCode(), "充值失败，每月充值已达上限，请使用支付宝充值");
                        }
                    }
                }
                //按照元计算
                String hjzDayAllMoney = Redis.str.get(hjzfMoneyDayAllKey);
                if (StringHandler.isNotEmpty(hjzDayAllMoney)) {
                    long hjzf = StringHandler.getLong(Config.pp.get("wallet.recharge.money.hjzf.day.all"));
                    if (hjzf > 0) {
                        if (StringHandler.getLong(StringHandler.isEmpty(hjzDayAllMoney) ? 0 : StringHandler.getLong(hjzDayAllMoney)) + StringHandler.getLong(rechargeCreate.getAmount()) > hjzf) {
                            SystemError.wrapBs(EnumType.ResponseCode.Fail.getCode(), "充值失败，银行卡充值已达每日上限");
                        }
                    }
                }
            }
        }
        // 数据验证
        rechargeCreate.check(uid);

        UserBank userBank = payService.getUserBankByUserIdHjzf(StringHandler.getLong(uid),rechargeCreate.getCardToken());
        if(StringHandler.isEmpty(userBank)){
            SystemError.wrapBs(EnumType.ResponseCode.ILLEGAL.getCode(), "银行卡不存在");
        }
        if(StringHandler.isEmpty(rechargeCreate.getOrderId())){
            Map<String,String> order = orderService.order(uid,rechargeCreate.getAmount(),5);
            rechargeCreate.setGoodsName(order.get("goodsName"));
            rechargeCreate.setOrderId(order.get("id"));
        }

        Map<String,Object> result = new HashMap<>();
        try {
            PayOrder payOrder = new PayOrder();
            payOrder.setBusyId(uid);
            payOrder.setOrderNo(rechargeCreate.getRequestId());
            payOrder.setProductName(rechargeCreate.getGoodsName());
            payOrder.setAmount(StringHandler.getLong(rechargeCreate.getAmount()));
            payOrder.setPayType(PayEnum.payMentType.BANK.getCode());
            payOrder.setPayStatus(PayEnum.PayStatus.NO_PAY.getCode());
            payOrder.setBusinessType(rechargeCreate.getBusinessType());
            payOrder.setOrderId(StringHandler.getLong(rechargeCreate.getOrderId()));
            payOrder.setPayChannel(5);
            // 保存银行卡信息
            payOrder.setMobile(userBank.getMobile());
            payOrder.setUserName(userBank.getUserName());
            payOrder.setCardNo(userBank.getCardNo());
            payOrder.setBankName(userBank.getBankName());
            MsgInfo msgInfo = HjzfHandler.paySms(payOrder,rechargeCreate.goodsName,1,userBank.linkId);
            if(msgInfo.isSuccess){
                payService.payOrder(payOrder);
                if(rechargeCreate.getBusinessType()==1){
                    Redis.key.increment(key);
                    Redis.key.setKeyTimeout(key,86400L);
                    Redis.key.increment(hjzfMoneyAllKey,payOrder.getAmount());
                    Redis.key.setKeyTimeout(hjzfMoneyAllKey,86400L);
                    Redis.key.increment(hjzfAllKey,payOrder.getAmount());
                    Redis.key.setKeyTimeout(hjzfAllKey,86400L);
//                    Redis.key.increment(moneyAllKey,payOrder.getAmount());
//                    Redis.key.setKeyTimeout(moneyAllKey,86400L);
                    Redis.key.increment(hjzfMoneyDayAllKey,StringHandler.getLong(rechargeCreate.getAmount())/100);
                    Redis.key.setKeyTimeout(hjzfMoneyDayAllKey,24*60*60L);
                }
                result.put("orderSn",payOrder.getOrderNo());
            }else{
                log.error("支付失败------------------"+msgInfo.errMsg);
                ResponseHandler.error("500","支付失败");
            }
        } catch (Exception e) {
            log.error("支付失败------------------",e);
            SystemError.wrapBs("500", "支付失败");
        }
        return ResponseHandler.success(result);
    }

    @RequestMapping("sms/pay")
    public String smsPay(@RequestAttribute String uid,
                          String orderSn,String smsCode) {
        if (Boolean.parseBoolean(Config.pp.get("trading.disable"))) {
            SystemError.wrapBs("500", "交易系统已关闭");
        }
        MsgInfo msgInfo = HjzfHandler.smsPay(orderSn,smsCode);
        if(!msgInfo.isSuccess){
            log.error("支付失败------------------"+msgInfo.errMsg);
            SystemError.wrapBs("500", "支付失败失败...");
        }
        return ResponseHandler.success();
    }

//    @RequestMapping("/trans")
//    public void trans(){
//        WithdrawRecordWait payOrder = new WithdrawRecordWait();
//        payOrder.amount = 1L;
//        payOrder.orderNo = BaseParam.getOrderSN();
//        payOrder.cardNo = "6226221102826515";
//        payOrder.userName = "但何非";
//        HjzfHandler.trans( payOrder);
//    }
}
